package it.softphone.commons.spring.config;


import it.softphone.commons.exception.NullParameterException;
import it.softphone.commons.service.LogAware;
import it.softphone.commons.service.config.ConfigurationServiceFactory;
import it.softphone.commons.spring.ApplicationConfig;

import javax.servlet.ServletContext;

import org.apache.commons.configuration.ConfigurationException;

public class BaseWebConfigSupport extends BaseConfigSupport implements LogAware {

	/**
	 * 
	 * @param resourceName
	 * @return
	 * @throws ConfigurationException
	 */
	public org.apache.commons.configuration.Configuration getBaseConfig( String resourceName ) throws ConfigurationException {
		if( null==resourceName ) throw new NullParameterException("resourceName");
		
		java.io.File confFile = getResourceAsFile( resourceName );
		
		if( confFile == null ) return super.getBaseConfig();
		
		org.apache.commons.configuration.Configuration conf = ConfigurationServiceFactory.getConfigurationService( confFile.toURI() );
		
		return conf;
		
	}
	
	/**
	 * 
	 * @return
	 */
	protected java.io.File getResourceAsFile( String resourceName ) {

		ServletContext sc = ApplicationConfig.getServletContext();
		
		if( sc==null ) {
			logger.warn( "Servlet Context is not set in ApplicationConfig!");
			return null;
		}
		
		String realPath = sc.getRealPath("/WEB-INF");
		
		java.io.File confFile = new java.io.File( realPath, resourceName);
		
		return confFile;
	}
	
	/**
	 * 
	 * @return
	 * @throws ConfigurationException
	 */
	@Override
	public org.apache.commons.configuration.Configuration getBaseConfig() throws ConfigurationException {
		return getBaseConfig(DEFAULT_CONFIG_PROPERTIES);
	}
}
